package com.threeti.mecool.core.domain.model;

import com.threeti.mecool.core.infrastructure.persistence.CommonConfigRepository;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.InvalidPropertiesFormatException;
import java.util.LinkedList;
import java.util.List;

@Service
public class Config {
    @Autowired private CommonConfigRepository configRepository;

    public String get(ConfigKey key) {
        CommonConfig commonConfig = configRepository.findOne(key.name());
        if (commonConfig == null) {
            commonConfig = insertDefault(key);
        }
        return commonConfig.getValue();
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    private CommonConfig insertDefault(ConfigKey key) {
        CommonConfig config = new CommonConfig(key.name(), key.getValue(), key.getComment());
        try {
            configRepository.save(config);
        } catch (Exception ignore) {
        }
        return config;
    }

    /**
     * underscore('_') separated
     * @param key key
     * @return int[]
     */
    public Integer[] getIntegerArray(ConfigKey key) throws InvalidPropertiesFormatException {
        String s = get(key);
        try {
            List<Integer> list = new LinkedList<Integer>();
            for (String v : StringUtils.split(s, '_')) {
                list.add(Integer.valueOf(v));
            }
            return list.toArray(new Integer[list.size()]);
        } catch (Exception e) {
            throw new InvalidPropertiesFormatException(String.format("参数配置错误 - %s[%s]\n%s", key.name(), s, key.getComment()));
        }
    }

    /**
     *
     * @param key key
     * @return int[2]
     * @throws InvalidPropertiesFormatException
     */
    public int[] getTimePeriod(ConfigKey key) throws InvalidPropertiesFormatException {
        Integer[] timePeriod = getIntegerArray(key);
        try {
            int from = timePeriod[0];
            int to = timePeriod[1];
            if (from == to || from < 0 || to < 0 ||
                    from / 100 > 23 || to / 100 > 23 ||
                    from % 100 > 59 || to % 100 > 59)
                throw new RuntimeException("");
            return new int[] {from, to};
        } catch (Exception e) {
            throw new InvalidPropertiesFormatException(String.format("参数配置错误 - %s\n%s", key.name(), key.getComment()));
        }
    }
}
